package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.controller.Response.R;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import com.itheima.untils.BaseContext;
import com.itheima.untils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    @PostMapping("/sendMsg")
    public R<String> getSendMsg(@RequestBody User user, HttpSession session){
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        session.setAttribute(user.getPhone(),code);
        log.info("验证码为:{}",code);
        return R.success("验证码生成成功");
    }

    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session){
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();
        String attribute = session.getAttribute(phone).toString();
        if (attribute.equals(code)){
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone,phone);
            User one = userService.getOne(queryWrapper);
            if (one==null){
                one.setPhone(phone);
                one.setStatus(1);
                userService.save(one);
            }else {
                session.setAttribute("user",one.getId());
            }
            return R.success(one);
        }
        return R.error("用户名或验证码错误");
    }
}
